<?php

namespace app\admin\controller;

use think\admin\Controller;
use think\facade\Db;
use think\facade\Log;

/**
 * 代码生成器
 * @class Generator
 * @package app\admin\controller
 */
class Generator extends Controller
{
    /**
     * 代码生成器首页
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '代码生成器';

        if ($this->request->isGet()) {
            // 获取数据库表列表
            try {
                $tables = Db::query('SHOW TABLES');
                $tableList = [];

                foreach ($tables as $table) {
                    $tableName = array_values($table)[0];
                    $tableList[] = [
                        'name' => $tableName,
                        'comment' => $this->getTableComment($tableName)
                    ];
                }

                $this->tableList = $tableList;
            } catch (\Exception $e) {
                $this->tableList = [];
            }

            $this->fetch();
        }
    }

    /**
     * 获取表字段信息
     * @auth true
     */
    public function getTableFields()
    {
        //try {
        $tableName = $this->request->param('table_name');

        if (empty($tableName)) {
            $this->error('表名不能为空');
        }

        // 调试信息
        $debugInfo = [
            'table_name' => $tableName,
            'request_method' => $this->request->method(),
            'post_data' => $this->request->post(),
            'get_data' => $this->request->get(),
        ];

        // 检查数据库连接
        try {
            $dbName = Db::query('SELECT DATABASE() as db')[0]['db'] ?? 'unknown';
            $debugInfo['database'] = $dbName;
        } catch (\Exception $e) {
            $debugInfo['database_error'] = $e->getMessage();
        }

        // 获取表DDL
        $sql = "SHOW CREATE TABLE `{$tableName}`";
        $debugInfo['sql'] = $sql;

        try {
            $createTable = Db::query($sql);
            $debugInfo['query_result_count'] = count($createTable);
        } catch (\Exception $e) {
            $debugInfo['query_error'] = $e->getMessage();
            $this->error('查询失败：' . $e->getMessage(), '', $debugInfo);
        }

        if (empty($createTable)) {
            $this->error('表不存在：' . $tableName, '', $debugInfo);
        }

        $ddl = $createTable[0]['Create Table'] ?? '';
        $debugInfo['has_ddl'] = !empty($ddl);
        $debugInfo['ddl_length'] = strlen($ddl);

        if (empty($ddl)) {
            $this->error('无法获取表结构', '', $debugInfo);
        }

        // 解析DDL获取字段信息
        $tableInfo = $this->parseDDL($ddl, $tableName);

        $debugInfo['fields_count'] = count($tableInfo['fields']);

        // 添加调试信息
        $tableInfo['_debug'] = $debugInfo;
        $this->success('获取成功', $tableInfo);

        //} catch (\Exception $e) {
        //    // 捕获所有异常，返回详细信息
        //    $errorInfo = [
        //        'message' => $e->getMessage(),
        //        'file' => $e->getFile(),
        //        'line' => $e->getLine(),
        //        'trace' => $e->getTraceAsString()
        //    ];
        //    $this->error('系统异常：' . $e->getMessage(), '', $errorInfo);
        //}
    }

    /**
     * 获取表DDL
     * @auth true
     */
    public function getTableDDL()
    {
        $tableName = $this->request->param('table_name');

        if (empty($tableName)) {
            $this->error('表名不能为空');
        }

        try {
            $sql = "SHOW CREATE TABLE `{$tableName}`";
            $createTable = Db::query($sql);
            $ddl = $createTable[0]['Create Table'] ?? '';

            $this->success('获取成功', '', ['ddl' => $ddl]);
        } catch (\Exception $e) {
            $this->error('获取失败：' . $e->getMessage());
        }
    }

    /**
     * 预览代码
     * @auth true
     */
    public function preview()
    {
        //try {
        $data = $this->request->post();
        $tableName = $data['table_name'] ?? '';

        if (empty($tableName)) {
            $this->error('表名不能为空');
        }

        // 获取表DDL（添加反引号）
        $sql = "SHOW CREATE TABLE `{$tableName}`";
        $createTable = Db::query($sql);
        $ddl = $createTable[0]['Create Table'] ?? '';

        // 解析DDL
        $tableInfo = $this->parseDDL($ddl, $tableName);

        // 如果前端传递了模块名称，则使用前端配置
        if (!empty($data['module_name'])) {
            $tableInfo['comment'] = $data['module_name'];
        }

        // 如果前端传递了字段配置，则使用前端配置
        if (!empty($data['fields_config'])) {
            $fieldsConfig = $data['fields_config'];
            foreach ($tableInfo['fields'] as &$field) {
                foreach ($fieldsConfig as $config) {
                    if ($config['name'] === $field['name']) {
                        $field['comment'] = $config['comment'] ?? $field['comment'];
                        $field['form_type'] = $config['form_type'] ?? $field['form_type'];
                        $field['required'] = $config['required'] ?? $field['required'];
                        $field['show_in_list'] = !isset($config['show_in_list']) || $config['show_in_list'] === 'true';
                        $field['show_in_form'] = !isset($config['show_in_form']) || $config['show_in_form'] === 'true';
                        //Log::info('field {field_name}  {field} config {config}'.PHP_EOL,[
                        //    'field_name' => $field['name'],
                        //    'config' => var_export($config,true),
                        //    'field' => var_export($field,true)
                        //]);
                        break;
                    }
                }
            }
        }
        // 生成代码
        $codes = $this->generateCode($tableInfo, $data);

        $this->success('预览成功', $codes);
        //} catch (\Exception $e) {
        //    $this->error('预览失败：' . $e->getMessage());
        //}
    }

    /**
     * 生成文件
     * @auth true
     */
    public function generate()
    {
        $data = $this->request->post(filter:'trim');
        $codes = $data['codes'] ?? [];
        $overwrite = $data['overwrite'] ?? 'skip'; // skip, overwrite, backup

        if (empty($codes)) {
            $this->error('没有要生成的代码');
        }

        //try {
        $result = [];
        foreach ($codes as $item) {
            $filePath = $item['path'] ?? '';
            $content = $item['content'] ?? '';
            if (empty($filePath) || empty($content)) {
                continue;
            }

            $fullPath = app()->getRootPath() . $filePath;
            $dir = dirname($fullPath);

            // 检查文件是否存在
            $fileExists = file_exists($fullPath);

            if ($fileExists) {
                if ($overwrite === 'skip') {
                    $result[] = [
                        'file' => $filePath,
                        'status' => 'skip',
                        'message' => '文件已存在，跳过'
                    ];
                    continue;
                } elseif ($overwrite === 'backup') {
                    // 备份文件
                    $backupPath = $fullPath . '.' . date('YmdHis') . '.bak';
                    copy($fullPath, $backupPath);
                }
                // overwrite === 'overwrite' 时直接覆盖，不做任何处理
            }

            // 创建目录
            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }

            // 写入文件
            file_put_contents($fullPath, $content);

            // 根据不同情况设置结果消息
            $statusMessage = '生成成功';
            if ($fileExists && $overwrite === 'backup') {
                $statusMessage = '已备份并覆盖';
            } elseif ($fileExists && $overwrite === 'overwrite') {
                $statusMessage = '已覆盖';
            }

            $result[] = [
                'file' => $filePath,
                'status' => 'success',
                'message' => $statusMessage
            ];
        }
        $this->success('文件生成完成',  $result);
        //} catch (\Exception $e) {
        //    $this->error('生成失败：' . $e->getMessage());
        //}
    }

    /**
     * 解析DDL
     */
    private function parseDDL($ddl, $tableName)
    {
        $tableInfo = [
            'table_name' => $tableName,
            'comment' => '',
            'fields' => []
        ];

        // 提取表注释 (修复正则表达式)
        if (preg_match("/CREATE TABLE `[^`]*`.*?COMMENT='([^']+)'/is", $ddl, $matches)) {
            $tableInfo['comment'] = $matches[1];
            // 如果注释的最后一个字符是"表"，则删除它
            if (mb_substr($tableInfo['comment'], -1) === '表') {
                $tableInfo['comment'] = mb_substr($tableInfo['comment'], 0, -1);
            }
        }

        // 提取字段信息
        preg_match_all('/`(\w+)`\s+(\w+)(\([^)]+\))?\s*([^,\n]*)/i', $ddl, $matches, PREG_SET_ORDER);

        foreach ($matches as $match) {
            $fieldName = $match[1];

            // 跳过主键id
            if (in_array($fieldName, ['PRIMARY', 'KEY', 'INDEX', 'UNIQUE'])) {
                continue;
            }

            $fieldType = strtolower($match[2]);
            $fieldLength = isset($match[3]) ? trim($match[3], '()') : '';
            $fieldExtra = $match[4] ?? '';

            $field = [
                'name' => $fieldName,
                'type' => $fieldType,
                'length' => $fieldLength,
                'comment' => '',
                'required' => stripos($fieldExtra, 'NOT NULL') !== false,
                'default' => null,
                'form_type' => $this->getFormType($fieldType, $fieldName),
                'show_in_list' => true,  // 默认在列表中显示
                'show_in_form' => true   // 默认在表单中显示
            ];

            // 提取注释
            if (preg_match("/COMMENT\s+'([^']+)'/i", $fieldExtra, $commentMatch)) {
                $field['comment'] = $commentMatch[1];
            }

            // 提取默认值
            if (preg_match("/DEFAULT\s+'?([^'\s,]+)'?/i", $fieldExtra, $defaultMatch)) {
                $field['default'] = $defaultMatch[1];
            }

            $tableInfo['fields'][] = $field;
        }

        return $tableInfo;
    }

    /**
     * 根据字段类型推断表单类型
     */
    private function getFormType($fieldType, $fieldName)
    {
        // 根据字段名推断
        if (strpos($fieldName, 'password') !== false) {
            return 'password';
        }
        if (in_array($fieldName, ['content', 'description', 'remark', 'introduce'])) {
            return 'textarea';
        }
        if (strpos($fieldName, 'image') !== false || strpos($fieldName, 'avatar') !== false ||
            strpos($fieldName, 'cover') !== false || strpos($fieldName, 'photo') !== false) {
            // 如果字段名包含images或者pics，使用可排序的多图上传
            if (strpos($fieldName, 'images') !== false || strpos($fieldName, 'pics') !== false || strpos($fieldName, 'photos') !== false) {
                return 'images_sortable';
            }
            return 'image';
        }
        if (strpos($fieldName, 'file') !== false) {
            return 'file';
        }
        if (in_array($fieldName, ['status', 'gender', 'is_show', 'is_hot'])) {
            return 'radio';
        }
        if (strpos($fieldName, '_at') !== false || strpos($fieldName, '_time') !== false ||
            strpos($fieldName, 'date') !== false) {
            return 'datetime';
        }

        // 根据类型推断
        switch ($fieldType) {
            case 'text':
            case 'longtext':
            case 'mediumtext':
                return 'textarea';
            case 'tinyint':
                return 'radio';
            case 'date':
                return 'date';
            case 'datetime':
            case 'timestamp':
                return 'datetime';
            case 'int':
            case 'bigint':
            case 'integer':
                return 'number';
            default:
                return 'text';
        }
    }

    /**
     * 生成代码
     */
    private function generateCode($tableInfo, $config)
    {
        $tableName = $tableInfo['table_name'];
        $className = $this->toCamelCase($tableName);
        $moduleComment = $tableInfo['comment'] ?: $className;

        $codes = [];

        // 生成Model
        if (!isset($config['generate_model']) || $config['generate_model']) {
            $codes[] = [
                'type' => 'model',
                'name' => $className . 'Dao.php',
                'path' => 'app/model/' . $className . 'Dao.php',
                'content' => $this->generateModel($tableInfo, $className)
            ];
        }

        // 生成Controller
        if (!isset($config['generate_controller']) || $config['generate_controller']) {
            $codes[] = [
                'type' => 'controller',
                'name' => $className . '.php',
                'path' => 'app/admin/controller/' . $className . '.php',
                'content' => $this->generateController($tableInfo, $className, $moduleComment)
            ];
        }

        // 生成View - 列表页
        if (!isset($config['generate_view']) || $config['generate_view']) {
            $codes[] = [
                'type' => 'view',
                'name' => 'index.html',
                'path' => 'app/admin/view/' . strtolower($this->toSnakeCase($className)) . '/index.html',
                'content' => $this->generateListView($tableInfo, $className, $moduleComment)
            ];

            // 生成View - 表单页
            $codes[] = [
                'type' => 'view',
                'name' => 'form.html',
                'path' => 'app/admin/view/' . strtolower($this->toSnakeCase($className)) . '/form.html',
                'content' => $this->generateFormView($tableInfo, $className, $moduleComment)
            ];

            // 生成View - 搜索表单
            $codes[] = [
                'type' => 'view',
                'name' => 'index_search.html',
                'path' => 'app/admin/view/' . strtolower($this->toSnakeCase($className)) . '/index_search.html',
                'content' => $this->generateSearchView($tableInfo, $className)
            ];
        }

        return $codes;
    }

    /**
     * 生成Model代码
     */
    private function generateModel($tableInfo, $className)
    {
        $tableName = $tableInfo['table_name'];
        $fields = $tableInfo['fields'];

        $properties = [];
        foreach ($fields as $field) {
            $type = $this->getPhpType($field['type']);
            $comment = $field['comment'] ?: $field['name'];
            $properties[] = " * @property {$type} \${$field['name']} {$comment}";
        }

        $propertiesStr = implode("\n", $properties);

        $code = <<<PHP
<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
{$propertiesStr}
 */
class {$className}Dao extends Model
{
    protected \$table = '{$tableName}';
    protected \$autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected \$createTime = 'create_at';
    protected \$updateTime = 'update_at';
}

PHP;

        return $code;
    }

    /**
     * 生成Controller代码
     */
    private function generateController($tableInfo, $className, $moduleComment)
    {
        $tableName = $tableInfo['table_name'];
        $fields = $tableInfo['fields'];

        // 检查是否有sort字段
        $hasSortField = false;
        foreach ($fields as $field) {
            if ($field['name'] === 'sort') {
                $hasSortField = true;
                break;
            }
        }

        // 生成搜索字段
        $searchFields = [];
        $equalFields = [];
        foreach ($fields as $field) {
            if (in_array($field['name'], ['name', 'title'])) {
                $searchFields[] = "->like('{$field['name']}')";
            }
            if (in_array($field['name'], ['status', 'type', 'category_id'])) {
                $equalFields[] = "->equal('{$field['name']}')";
            }
        }

        $searchStr = implode("\n            ", array_merge($equalFields, $searchFields));
        if (empty($searchStr)) {
            $searchStr = '';
        } else {
            $searchStr = "\n            " . $searchStr;
        }

        // 生成排序语句
        $orderStr = $hasSortField ? "->order('sort DESC, id DESC')" : "->order('id DESC')";

        // 生成排序方法（如果有sort字段）
        $sortMethod = '';
        if ($hasSortField) {
            $sortMethod = <<<'PHP'

    /**
     * 修改排序
     * @auth true
     */
    public function sort()
    {
        $this->_save($this->table, $this->_vali([
            'sort.require' => '排序值不能为空！',
        ]));
    }
PHP;
        }

        $code = <<<PHP
<?php

namespace app\admin\controller;

use app\model\\{$className}Dao;
use think\admin\Controller;

/**
 * {$moduleComment}管理
 * @class {$className}
 * @package app\admin\controller
 */
class {$className} extends Controller
{
    protected \$table = '';

    protected function initialize()
    {
        \$this->table = {$className}Dao::query();
    }

    /**
     * {$moduleComment}列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        \$this->title = '{$moduleComment}管理';
        \$this->_query(\$this->table){$searchStr}
            {$orderStr}
            ->dateBetween('create_at')
            ->page();
    }

    /**
     * 添加{$moduleComment}
     * @auth true
     */
    public function add()
    {
        \$this->_form(\$this->table, 'form');
    }

    /**
     * 编辑{$moduleComment}
     * @auth true
     */
    public function edit()
    {
        \$this->_form(\$this->table, 'form');
    }

    /**
     * 删除{$moduleComment}
     * @auth true
     */
    public function remove()
    {
        \$this->_applyFormToken();
        \$this->_delete(\$this->table);
    }

    /**
     * 修改状态
     * @auth true
     */
    public function state()
    {
        \$this->_save(\$this->table, \$this->_vali([
            'status.in:0,1' => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }{$sortMethod}
}

PHP;

        return $code;
    }

    /**
     * 生成列表视图
     */
    private function generateListView($tableInfo, $className, $moduleComment)
    {
        $fields = $tableInfo['fields'];
        $thList = [];
        $tdList = [];
        $hasSortField = false;
        foreach ($fields as $field) {
            // 检查是否有sort字段
            if ($field['name'] === 'sort') {
                $hasSortField = true;
                continue; // 跳过sort字段，它会单独显示在第一列
            }

            // 跳过id字段，它会单独显示
            if ($field['name'] === 'id') {
                continue;
            }

            // 检查是否在列表中显示
            if (!isset($field['show_in_list']) || $field['show_in_list'] !== false) {
                $comment = $field['comment'] ?: $field['name'];
                $thList[] = "            <th class='text-left nowrap'>{$comment}</th>";

                // 根据字段类型生成不同的TD
                if (in_array($field['name'], ['image', 'avatar', 'cover', 'photo'])) {
                    $tdList[] = <<<HTML
            <td class='text-left'>
                <img width="75" src="{\$vo.{$field['name']}|default=''}" data-tips-image>
            </td>
HTML;
                } elseif ($field['name'] === 'title'){
                    $tdList[] = <<<HTML
            <td class='text-left' title="{\$vo.{$field['name']}|default=''}">
                {\$vo.{$field['name']}|default=''|sub_str=###,',16}
            </td>
HTML;
                } elseif ($field['name'] === 'status') {
                    $tdList[] = <<<HTML
            <td class='text-left'>
                {switch vo.status }
                {case 1}<span class="layui-badge layui-bg-green">正常</span>{/case}
                {case 0}<span class="layui-badge">隐藏</span>{/case}
                {default /}<span class="layui-badge-rim">未知</span>
                {/switch}
            </td>
HTML;

                } elseif (strpos($field['name'], '_at') !== false) {
                    $tdList[] = <<<HTML
            <td class="text-left nowrap">
                {\$vo.{$field['name']}|default=''}
            </td>
HTML;
                } else {
                    $tdList[] = <<<HTML
            <td class='text-left'>
                {\$vo.{$field['name']}|default=''}
            </td>
HTML;
                }
            }
        }

        $thStr = implode("\n", $thList);
        $tdStr = implode("\n", $tdList);

        $snakeName = $this->toSnakeCase($className);

        // 如果有sort字段，添加排序列
        $sortThHtml = '';
        $sortTdHtml = '';
        if ($hasSortField) {
            $sortThHtml = <<<HTML
            <th class='list-table-sort-td'>
                <button type="button" data-reload class="layui-btn layui-btn-xs">刷 新</button>
            </th>
HTML;
            $sortTdHtml = <<<HTML
            <td class='list-table-sort-td'>
                <input data-action-blur="{:request()->url()}" data-value="id#{\$vo.id};action#sort;sort#{value}" data-loading="false" value="{\$vo.sort}" class="list-sort-input">
            </td>
HTML;
        }

        $code = <<<HTML
{extend name='main'}

{block name="button"}
{if auth("add")}
<button data-modal='{:url("add")}' data-area = "['1200px','80dvh']" class='layui-btn layui-btn-sm layui-btn-primary'>添加</button>
{/if}
{/block}

{block name="content"}

<div class="think-box-shadow">
    <table class="layui-table margin-top-10" lay-skin="line">
        {notempty name='list'}
        <thead>
        <tr>
{$sortThHtml}
            <th class='text-left nowrap'>ID</th>
{$thStr}
            <th class='text-center nowrap'>操作</th>
        </tr>
        </thead>
        {/notempty}
        <tbody>
        {foreach \$list as \$key=>\$vo}
        <tr data-dbclick>
{$sortTdHtml}
            <td class='text-left'>{\$vo.id}</td>
{$tdStr}
            <td class='text-center operator'>
                {if auth("edit")}
                <a data-dbclick class="layui-btn layui-btn-sm" data-area="['1200px','80dvh']" data-title="编辑" data-modal='{:url("edit")}?id={\$vo.id}'>编辑</a>
                {/if}
                
                {if auth("state")}
                {if \$vo.status == 1}
                <a class="layui-btn layui-btn-warm layui-btn-sm" data-action='{:url("state")}' data-value="id#{\$vo.id};status#0">禁用</a>
                {else}
                <a class="layui-btn layui-btn-sm" data-action='{:url("state")}' data-value="id#{\$vo.id};status#1">启用</a>
                {/if}
                {/if}
                
                {if auth("remove")}
                <a class="layui-btn layui-btn-danger layui-btn-sm" data-confirm="确定要删除吗?" data-action="{:url('remove')}" data-value="id#{\$vo.id}" data-csrf="{:systoken('remove')}">删除</a>
                {/if}
            </td>
        </tr>
        {/foreach}
        </tbody>
    </table>
    {empty name='list'}<span class="notdata">没有记录哦</span>{else}{\$pagehtml|raw|default=''}{/empty}
</div>
<style>
.operator a{margin-bottom: 5px;}
</style>
{/block}

HTML;

        return $code;
    }

    /**
     * 生成表单视图
     */
    private function generateFormView($tableInfo, $className, $moduleComment)
    {
        $fields = $tableInfo['fields'];

        $formFields = [];

        foreach ($fields as $field) {
            // 检查是否在表单中显示并且不是系统字段
            if ((!isset($field['show_in_form']) || $field['show_in_form'] !== false) &&
                !in_array($field['name'], ['id', 'create_at', 'update_at', 'delete_at'])) {

                $comment = $field['comment'] ?: $field['name'];
                $required = $field['required'] ? 'required' : '';

                switch ($field['form_type']) {
                    case 'textarea':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <textarea placeholder="请输入{$comment}" {$required} class="layui-textarea" name="{$field['name']}">{\$vo.{$field['name']}|default=""}</textarea>
                            </div>
                        </div>                  
                    </div>
HTML;
                        break;

                    case 'image':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item margin-bottom-5">
                            <div class="help-label"><b>{$comment}</b></div>
                            <div class="layui-textarea help-images">
                                <input type="hidden" value="{\$vo.{$field['name']}|default=''}" name="{$field['name']}">
                            </div>
                            <script>
                             \$('[name={$field['name']}]').uploadOneImage();
                            </script>
                        </div>
                    </div>
HTML;
                        break;

                    case 'images':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item margin-bottom-5">
                            <div class="help-label"><b>{$comment}</b></div>
                            <div class="layui-textarea help-images">
                                <input type="hidden" value="{\$vo.{$field['name']}|default=''}" name="{$field['name']}">
                            </div>
                            <script>
                            \$('[name={$field['name']}]').uploadMultipleImage();
                            </script>
                        </div>
                    </div>
HTML;
                        break;

                    case 'images_sortable':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item margin-bottom-5">
                            <div class="help-label"><b>{$comment}</b></div>
                            <div class="layui-textarea help-images">
                                <input type="hidden" value="{\$vo.{$field['name']}|default=''}" name="{$field['name']}">
                            </div>
                            <script>
                              \$('[name={$field['name']}]').uploadSortableImages();
                            </script>
                        </div>
                    </div>
HTML;
                        break;

                    case 'file':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item">
                            <label class="layui-form-label"><b>{$comment}</b></label>
                            <div class="layui-input-block">
                                <input type="text" class="layui-input" name="{$field['name']}" value="{\$vo.{$field['name']}|default=''}" placeholder="请上传{$comment}" readonly>
                                <button type="button" class="layui-btn layui-btn-sm" id="upload-{$field['name']}">
                                    <i class="layui-icon">&#xe67c;</i>上传文件
                                </button>
                            </div>
                        </div>
                    </div>
                    <script>
                    layui.use(['upload', 'jquery'], function(){
                        var upload = layui.upload;
                        var \$ = layui.jquery;
                        upload.render({
                            elem: '#upload-{$field['name']}',
                            url: '{:url("api.upload/file")}',
                            accept: 'file',
                            done: function(res){
                                if(res.code === 1){
                                    \$('[name={$field['name']}]').val(res.data.url);
                                    layer.msg('上传成功');
                                } else {
                                    layer.msg(res.msg || '上传失败');
                                }
                            }
                        });
                    });
                    </script>
HTML;
                        break;

                    case 'editor':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <textarea placeholder="请输入{$comment}" {$required} class="layui-textarea" name="{$field['name']}">{\$vo.{$field['name']}|default=""|raw}</textarea>
                            </div>
                        </div>                    
                    </div>
                    <script>
                    require(['ckeditor', 'angular'], function () {
                       window.createEditor('[name="{$field['name']}"]', {height: 500});
                    });
                    </script>
HTML;
                        break;

                    case 'radio':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="layui-input">
                                {foreach [['title'=>'启用','value'=>1,'is_default'=>1],['title'=>'禁用','value'=>0,'is_default'=>0]] as \$v }
                                {if isset(\$vo.{$field['name']}) && \$vo.{$field['name']}==\$v.value || \$v.is_default==1 && !isset(\$vo.{$field['name']}) }
                                <input type="radio" name="{$field['name']}" checked title="{\$v.title}" value="{\$v.value}">
                                {else /}<input type="radio" name="{$field['name']}" title="{\$v.title}" value="{\$v.value}">
                                {/if}
                                {/foreach}
                            </div>
                        </div>                   
                    </div>
HTML;
                        break;
                    case 'switch':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="layui-input">
                                <input type="checkbox" name="{$field['name']}" lay-skin="switch" lay-text="ON|OFF" value="1" {\$vo.{$field['name']}==1?'checked':''}>
                            </div>
                        </div>                   
                    </div>
HTML;
                        break;
                    case 'checkbox':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs12">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="layui-input">
                                <input type="checkbox" name="{$field['name']}[]" title="选项1" value="1" lay-skin="primary">
                                <input type="checkbox" name="{$field['name']}[]" title="选项2" value="2" lay-skin="primary">
                                <input type="checkbox" name="{$field['name']}[]" title="选项3" value="3" lay-skin="primary">
                            </div>
                        </div>
                    </div>
HTML;
                        break;
                    case 'select':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="layui-input-block">
                                <select {$required}  name="{$field['name']}" lay-search>
                                    <option value=''>-- {:lang('全部')} --</option>
                                    {foreach [1=>'八大赛道',2=>'线上会刊',3=>'产业研究',4=>'标准'] as \$k=>\$v}
                                    {if isset(\$vo.{$field['name']}) and \$vo.{$field['name']} eq \$k.""}
                                    <option selected value="{\$k}">{\$v}</option>
                                    {else}
                                    <option value="{\$k}">{\$v}</option>
                                    {/if}{/foreach}
                                </select>
                            </div>
                        </div>
                    </div>
HTML;
                        break;

                    case 'date':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="text" data-date-input name="{$field['name']}" {$required} value="{\$vo.{$field['name']}|default=''}" placeholder="请选择{$comment}" class="layui-input">
                            </div>
                        </div>
                    </div>
HTML;
                        break;

                    case 'datetime':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="text" data-date-input="datetime name="{$field['name']}" {$required} value="{\$vo.{$field['name']}|default=''}" placeholder="请选择{$comment}" class="layui-input">
                            </div>
                        </div>
                    </div>
HTML;
                        break;

                    case 'password':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="password"  name="{$field['name']}" {$required} value="{\$vo.{$field['name']}|default=''}" placeholder="请选择{$comment}" class="layui-input">
                            </div>
                        </div>                   
                    </div>
HTML;
                        break;

                    case 'color':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="text" class="layui-input" name="{$field['name']}" value="{\$vo.{$field['name']}|default='#000000'}" id="color-{$field['name']}">
                            </div>
                        </div>
                    </div>
                    <script>
                    layui.use(['colorpicker', 'jquery'], function(){
                        var colorpicker = layui.colorpicker;
                        var \$ = layui.jquery;
                        colorpicker.render({
                            elem: '#color-{$field['name']}',
                            color: '{\$vo.{$field['name']}|default="#000000"}',
                            done: function(color){
                                \$('[name={$field['name']}]').val(color);
                            }
                        });
                    });
                    </script>
HTML;
                        break;

                    case 'number':
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="number"  name="{$field['name']}" {$required} value="{\$vo.{$field['name']}|default=''}" placeholder="请输入{$comment}" class="layui-input">
                            </div>
                        </div>
                    </div>
HTML;
                        break;

                    default: // text
                        $formFields[] = <<<HTML
                    <div class="layui-col-xs6">
                        <div class="layui-form-item">
                            <label class="color-green font-w7"><b>{$comment}</b></label>
                            <div class="">
                                <input type="text"  name="{$field['name']}" {$required} value="{\$vo.{$field['name']}|default=''}" placeholder="请输入{$comment}" class="layui-input">
                            </div>
                        </div>
                    </div>
HTML;
                        break;
                }
            }
        }

        $formFieldsStr = implode("\n", $formFields);

        $code = <<<HTML
{extend name='main'}

{block name="button"}
<button data-target-submit class='layui-btn layui-btn-sm'>{:lang('保存数据')}</button>
<button data-target-backup class="layui-btn layui-btn-sm layui-btn-danger">{:lang('取消编辑')}</button>
{/block}

{block name="content"}
<div class="think-box-shadow">
    <form action="{:sysuri()}" method="post" data-auto="true" class="layui-form layui-card">
        <div class="layui-card-body">
            <div class="layui-row layui-col-space10">
{$formFieldsStr}
            </div>

            <div class="hr-line-dashed"></div>
            {notempty name='vo.id'}<input name="id" value="{\$vo.id}" type="hidden"/>{/notempty}
            <div class="layui-form-item text-center">
                <button class="layui-btn" type="submit">{:lang('保存数据')}</button>
                <button data-target-backup class="layui-btn layui-btn-danger" type="button">{:lang('取消编辑')}</button>
            </div>
        </div>
    </form>
</div>

{/block}

HTML;

        return $code;
    }

    /**
     * 生成搜索视图
     */
    private function generateSearchView($tableInfo, $className)
    {
        $fields = $tableInfo['fields'];

        $searchFields = [];

        foreach ($fields as $field) {
            // 检查是否在列表中显示
            if (!isset($field['show_in_list']) || $field['show_in_list'] !== false) {
                if (in_array($field['name'], ['name', 'title'])) {
                    $comment = $field['comment'] ?: $field['name'];
                    $searchFields[] = <<<HTML
    <div class="layui-inline">
        <label class="layui-form-label">{$comment}</label>
        <div class="layui-input-inline">
            <input type="text" name="{$field['name']}" class="layui-input" placeholder="请输入{$comment}">
        </div>
    </div>
HTML;
                } elseif ($field['name'] === 'status') {
                    $searchFields[] = <<<HTML
    <div class="layui-inline">
        <label class="layui-form-label">状态</label>
        <div class="layui-input-inline">
            <select name="status" class="layui-select">
                <option value="">全部</option>
                <option value="1">启用</option>
                <option value="0">禁用</option>
            </select>
        </div>
    </div>
HTML;
                }
            }
        }

        $searchFieldsStr = implode("\n", $searchFields);

        $code = <<<HTML
<form class="layui-form layui-form-pane form-search" action="{\$Request.url}" onsubmit="return false" method="get">
{$searchFieldsStr}
    <div class="layui-inline">
        <label class="layui-form-label">创建时间</label>
        <div class="layui-input-inline">
            <input data-date-range class="layui-input" name="create_at" value="" placeholder="请选择时间范围">
        </div>
    </div>
    <div class="layui-inline">
        <button class="layui-btn layui-btn-primary" type="submit"><i class="layui-icon">&#xe615;</i> 搜 索</button>
    </div>
</form>

HTML;

        return $code;
    }

    /**
     * 获取表注释
     */
    private function getTableComment($tableName)
    {
        try {
            $sql = "SELECT TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?";
            $result = Db::query($sql, [$tableName]);
            return $result[0]['TABLE_COMMENT'] ?? '';
        } catch (\Exception $e) {
            return '';
        }
    }

    /**
     * 转换为驼峰命名
     */
    private function toCamelCase($str)
    {
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $str)));
    }

    /**
     * 转换为蛇形命名
     */
    private function toSnakeCase($str)
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
    }

    /**
     * 获取PHP类型
     */
    private function getPhpType($dbType)
    {
        $typeMap = [
            'int' => 'int',
            'integer' => 'int',
            'bigint' => 'int',
            'tinyint' => 'int',
            'smallint' => 'int',
            'mediumint' => 'int',
            'float' => 'float',
            'double' => 'float',
            'decimal' => 'float',
            'varchar' => 'string',
            'char' => 'string',
            'text' => 'string',
            'longtext' => 'string',
            'mediumtext' => 'string',
            'date' => 'string',
            'datetime' => 'string',
            'timestamp' => 'string',
        ];

        return $typeMap[$dbType] ?? 'string';
    }
}